package com.seecen.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.seecen.mapper.ProductMapper;
import com.seecen.pojo.Order;
import com.seecen.pojo.Product;
import com.seecen.service.OrderService;
import com.seecen.mapper.OrderMapper;
import com.seecen.service.ProductService;
import com.seecen.utils.Result;
import com.seecen.utils.ResultCodeEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
* @author 桃子
* @description 针对表【order】的数据库操作Service实现
* @createDate 2025-07-21 14:26:52
*/
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order>
    implements OrderService{


    @Autowired
    private ProductService productService;

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private ProductMapper productMapper;
    @Override
    @Transactional
    public Result createOrder(Order order) {
        //创建订单，判断该商品是否存在，检查库存
        // 1. 查询商品并校验库存
        LambdaQueryWrapper<Product> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Product::getProductId,order.getProductId())
                .eq(Product::getStatus, 0) // 只查询上架商品
                .gt(Product::getStock, 0) ;// 库存大于0

        Product product = productMapper.selectOne(wrapper);

        //商品不存在
        if (product == null) {
            return Result.build(null, ResultCodeEnum.PASSWORD_ERROR);
        }

        //库存不足
        if (product.getStock() < order.getQuantity()) {
            return Result.build(null, ResultCodeEnum.PASSWORD_ERROR);

        }

        //扣减库存
//        LambdaQueryWrapper<Product> wrapper1 = new LambdaQueryWrapper<>();
//        wrapper1.eq(Product::getProductId, order.getProductId())
//                .eq(Product::getStock, product.getStock());

        // 2. 扣减库存（使用CAS乐观锁）
        int updateCount = productMapper.update(null,
                new LambdaUpdateWrapper<Product>()
                        .eq(Product::getProductId, order.getProductId())
                        .eq(Product::getStock, product.getStock()) // 版本校验
                        .setSql("stock = stock - " + order.getQuantity())
        );

        // 库存已被其他操作修改
        if (updateCount == 0) {
            return Result.build(null, ResultCodeEnum.PASSWORD_ERROR);
        }


        //创建订单
        // 3. 创建订单
        Order newOrder = new Order();
        newOrder.setUserId(order.getUserId());
        newOrder.setProductId(order.getProductId());
        newOrder.setQuantity(order.getQuantity());
        newOrder.setOrderCreateTime(new Date());

        System.out.println("newOrder = " + newOrder);
        int insert = orderMapper.insert(newOrder);
        if(insert <= 0){
            return Result.build(null,ResultCodeEnum.PASSWORD_ERROR);
        }

        System.out.println("insert = " + insert);

        // 4. 返回订单详情
//        return Result.ok(newOrder);
//        HashMap orderMap = new HashMap();
//        orderMap.put("userId",order.getUserId());
//        orderMap.put("productId",order.getProductId());
//        orderMap.put("quantity",order.getQuantity());
//        orderMap.put("orderCreateTime",new Date());

        return Result.ok(newOrder);
    }

    @Override
    public Result listOrdersById(Integer userId) {

//        LambdaQueryWrapper<Order> wrapper = new LambdaQueryWrapper<>();
//        wrapper.eq(Order::getUserId,userId);
//        Order order = orderMapper.selectById(userId);
//
//        Map data = new HashMap();
//
//        data.put("order",order);
//
//        return Result.ok(data);

        List<Order> orderList = orderMapper.selectList(
                new LambdaQueryWrapper<Order>()
                        .eq(Order::getUserId, userId)
                        .orderByDesc(Order::getOrderCreateTime) // 按创建时间降序
        );
        return Result.ok(orderList); // 直接返回订单列表
    }

    @Override
    public Result payOrder(Integer orderId) {
        return null;
    }
}




